package com.pan.mapping;

import com.pan.entity.PosNameMapper;

import java.lang.reflect.Field;
import java.util.function.Function;

/**
 *
 * @param <T> 是映射属性的类型
 */
public class CellToField<T> {


    private Field field;

    private PosNameMapper<T> posNameMapper;

    public CellToField() {
    }

    public CellToField(PosNameMapper<T> posNameMapper, Field field) {
        this.field = field;
        this.posNameMapper = posNameMapper;
    }


    public <R> R fieldSet(R target, String value){
        field.setAccessible(true);
        try {
            field.set(
                    target,
                    posNameMapper.getMapper()!=null ?
                            posNameMapper.getMapper().apply(value):
                            value
            );
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return target;
    }

    public <R> R fieldSet(R target, Object value){
        field.setAccessible(true);
        try {
            field.set(target,value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return target;
    }

    public <R> T fieldGet(R object){
        field.setAccessible(true);
        T result;
        try {
            result = (T) field.get(object);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public <R> String fieldGetString(R object){
        field.setAccessible(true);
        Object value;
        try {
            value = field.get(object);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        Function<T, String> reverseMapper = this.getPosNameMapper().getReverseMapper();
        String result = reverseMapper == null?
                String.valueOf(value) : reverseMapper.apply((T) value);
        return result;

    }

    public Field getField() {
        return field;
    }

    public PosNameMapper<T> getPosNameMapper() {
        return posNameMapper;
    }
}
